<?php
/**
 * 角色管理
 * 2018/11/5
 * ╔═════╗                 ╔═╗ ╔═╗
 * ║ ╔═══╝                 ║ ║ ║ ║
 * ║ ╚═══╦══╦══╦═════╦═════╣ ╚═╝ ║
 * ╚═══╗ ║  ║  ║  ║  ║  ║  ╠═╗ ╔═╝
 * ╔═══╝ ║  ║  ║  ║  ║  ║  ║ ║ ║
 * ╚═════╩═════╩══╩══╩══╩══╝ ╚═╝
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\View;
use App\Models\RoleHasPermission;
use Illuminate\Http\Request;
use App\Models\Role;
use Spatie\Permission\Models\Permission;



class RoleController extends Controller
{
    function __construct()
    {
        $this->middleware('permission');
    }


    public function index(Request $request)
    {
        if (View::exists('Admin/role/index')) {
            $info = Role::withCount('modelHasAdminer')->where('id', '<>', 1)->orderBy('id','desc')->paginate($request->get('limit',30))->toArray();
            if($request->ajax()){
                $data = [
                    'code' => 0,
                    'msg'   => '正在请求中...',
                    'count' => $info['total'],
                    'data'  => $info['data']
                ];
                return response()->json($data);
            }else{
                return view('Admin/role/index',compact('info'));
            }
        } else {
            return 'View Not Found';
        }
    }

    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $this->validate($request, ['name' => 'required'],['name.required'=>'请填写角色名']);
            $rs = Role::where($request->all('name'))->first();
            if($rs){
                flash('角色名重复')->overlay();
                return redirect()->back();
            }
            if( $role = Role::create($request->only('name','comment')) ) {
                $role->syncPermissions($request->get('permissions', []));
                flash('添加成功')->overlay();
                return redirect('admin/role');
            }
        }else{
            if (View::exists('Admin/role/add')) {
                $permission = Permission::where('parentid',0)->orderBy('weight','desc')->get()->keyBy('id')->toArray();
                $data = array();
                foreach ($permission as $k=>$v){
                    $data[$v['id']] = $v;
                    $child = Permission::where('parentid',$v['id'])->where('id', '<>', 16)->orderBy('weight','desc')->get()->keyBy('id')->toArray();
                    if(count($child)){
                        $data[$v['id']]['child'] = $child;
                        foreach ($child as $key => $value) {
                            $childnode = Permission::where('parentid',$value['id'])->orderBy('weight','desc')->get()->keyBy('id')->toArray();
                            if(count($childnode)){
                                $data[$v['id']]['child'][$value['id']]['child'] = $childnode;
                            }
                        }
                    }
                }
                return view('Admin/role/add',compact('data'));
            } else {
                return 'View Not Found';
            }
        }
    }

    public function edit(Request $request)
    {
        if ($request->isMethod('post')) {
            $id = $request->input('id');
            $this->validate($request, ['name' => 'required'],['name.required'=>'请填写角色名']);
            $role = Role::find($id);
            if($role) {
                $permissions = $request->get('permissions', []);
                $role->whereId($id)->update(['name'=>$request->get('name'),'comment'=>$request->get('comment')]);
                $role->syncPermissions($permissions);
                flash('修改成功')->overlay();
            }else{
                flash('修改成功')->overlay();
            }
            return redirect('admin/role');
        }else{
            $id = $request->input('id');
            $roles = role::find($id);
            $permission = Permission::where('parentid',0)->orderBy('weight','desc')->get()->keyBy('id')->toArray();

            $data = array();
            foreach ($permission as $k=>$v){
                $data[$v['id']] = $v;
                $data[$v['id']]['own'] = $roles->hasPermissionTo($v['id']) ? 'checked' : false;
                $child = Permission::where('parentid',$v['id'])->where('id', '<>', 16)->orderBy('weight','desc')->get()->keyBy('id')->toArray();
                if(count($child)){
                    $data[$v['id']]['child'] = $child;

                    foreach ($child as $key => $value) {
                        $data[$v['id']]['child'][$value['id']]['own'] = $roles->hasPermissionTo($value['id']) ? 'checked' : false ;
                        $childnode = Permission::where('parentid',$value['id'])->orderBy('weight','desc')->get()->keyBy('id')->toArray();
                        if(count($childnode)){
                            $data[$v['id']]['child'][$value['id']]['child'] = $childnode;
                            foreach ($childnode as $key3 => $item3) {
                                $data[$v['id']]['child'][$value['id']]['child'][$item3['id']]['own'] = $roles->hasPermissionTo($item3['id']) ? 'checked' : false ;
                            }

                        }
                    }
                }
            }
            //dd($data);
            return view('/Admin/role/edit',compact('roles','data'));
        }
    }


    public function destroy(Request $request)
    {
        $id = $request->get('id');
        if(Role::destroy($id)){
            RoleHasPermission::where('role_id',$id)->delete();
            $data = [
                'code' => 1,
                'url' => '/admin/role',
                'msg' => '删除成功',
            ];
        }else{
            $data = [
                'code' => 0,
                'msg' => '删除失败',
            ];
        }
        return response()->json($data);
    }




}